function initCesiumXXX(id, token) {
  Cesium.Ion.defaultAccessToken = token;
  const viewer = new Cesium.Viewer(id, {
    animation: false, //显示动画
    timeline: false, //显示时间轴
    fullscreenButton: false, //显示全屏按钮
    vrButton: false, //显示vr按钮
    geocoder: false, //显示地理编码搜索框
    homeButton: false, //显示返回初始视角按钮
    sceneModePicker: false, //显示场景模式选择器（2d/3d/Columbus View）
    baseLayerPicker: false, //显示底图选择器
    navigationHelpButton: false, //显示导航帮助按钮
    infoBox: false, //显示信息框
    selectionIndicator: false, //显示选择指示器
  });
  //帧率/延迟显示
  // viewer.scene.debugShowFramesPerSecond = true;
  // 隐藏版权信息（非配置项，需单独设置）
  viewer.cesiumWidget.creditContainer.style.display = "none";
  // 笛卡尔坐标系的设置方法
  viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(104.06, 30.67, 3000000),
  });
  return viewer;
}
function changemap(viewer, id) {
  const option = [
    {
      id: "初始地图",
      provider: () => Cesium.createWorldImagery(),
    },
    {
      id: "ArcGIS(内置)",
      provider: () =>
        new Cesium.ArcGisMapServerImageryProvider({
          url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
          layers: "0",
        }),
    },
    {
      id: "OSM(内置)",
      provider: () =>
        new Cesium.OpenStreetMapImageryProvider({
          url: "https://{s}.tile.openstreetmap.org",
        }),
    },
    {
      id: "Google地图",
      provider: () =>
        new Cesium.UrlTemplateImageryProvider({
          assetId: "googleMapTile",
          url: "http://mt{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}",
          subdomains: ["0", "1", "2", "3"],
          credit: "Google Maps",
        }),
    },
    {
      id: "OSM",
      provider: () =>
        new Cesium.UrlTemplateImageryProvider({
          url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", // 瓦片 URL 模板，支持 {x}, {y}, {z}, {s} 等占位符。
          subdomains: ["a", "b", "c"], // 对应 {s}  // 子域名列表，用于轮询请求避免服务器限制。
          credit: "OpenStreetMap Contributors", // 地图版权信息（显示在右下角）
          minimumLevel: 0, // 最小缩放级别（通常为 0） 默认0
          maximumLevel: 19, // 最大缩放级别（根据服务支持调整）默认18
        }),
    },
    {
      id: "本地地图",
      provider: () =>
        new Cesium.UrlTemplateImageryProvider({
          url: "mapTile/{z}/{x}/{y}.png", // 瓦片 URL 模板，支持 {x}, {y}, {z}, {s} 等占位符。
          // subdomains: ["a", "b", "c"], // 对应 {s}  // 子域名列表，用于轮询请求避免服务器限制。
          // credit: "OpenStreetMap Contributors", // 地图版权信息（显示在右下角）
          minimumLevel: 0, // 最小缩放级别（通常为 0） 默认0
          maximumLevel: 10, // 最大缩放级别（根据服务支持调整）默认18
        }),
    },
  ];
  let changeobj = option.find((i) => i.id == id);
  if (!changeobj) {
    console.log("寻找的地图名不存在！");
  }
  viewer.imageryLayers.removeAll();
  console.log("寻找到的对应方法", changeobj);
  try {
    const provider = changeobj.provider();
    viewer.imageryLayers.addImageryProvider(provider);
    console.log(`已切换到: ${changeobj.id}`);
  } catch (error) {
    console.error("地图加载失败:", error);
  }
}
//longitude是经度 latitude是纬度
function positionToXXX(viewer, longitude, latitude, Height) {
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, Height),
    duration: 3,
  });
}
function drawPointToXXX(viewer, id, longitude, latitude) {
  let point = viewer.entities.add({
    id: id,
    position: Cesium.Cartesian3.fromDegrees(longitude, latitude, 0),
    point: {
      color: Cesium.Color.RED, //点的颜色（默认白色）
      pixelSize: 10, //像素大小（默认1）
      outlineColor: Cesium.Color.BLACK, //轮廓颜色
      outlineWidth: 2, //轮廓宽度
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, //贴地模式
    },
  });
}
function pointPositionToXXX(viewer, id) {
  //1.拿到点
  let entity = viewer.entities.getById(id);
  //2.获取实体的位置信息 但是获取到的是Cartesian3 坐标 （三维笛卡尔坐标）
  let position = entity.position.getValue();
  //3.转化为Cartogaphic格式
  let cartographic = Cesium.Cartographic.fromCartesian(position);
  // 4.转化为经纬度
  let longitude = Cesium.Math.toDegrees(cartographic.longitude);
  let latitude = Cesium.Math.toDegrees(cartographic.latitude);
  let height = cartographic.height;
  let currentCartographic = viewer.camera.positionCartographic;
  console.log(currentCartographic);
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(
      longitude,
      latitude,
      currentCartographic.height
    ),
  });
}
function drawLineToXXX(viewer, id, lineArray) {
  const positions = Cesium.Cartesian3.fromDegreesArrayHeights(lineArray);
  let line = viewer.entities.add({
    id: id,
    polyline: {
      width: 10,
      positions: positions,
      material: new Cesium.PolylineGlowMaterialProperty({
        color: Cesium.Color.RED,
      }),
      clampToGround: false,
    },
  });
}
function linePositionToXXX(viewer, id) {
  //需要先获取线的实体
  let entity = viewer.entities.getById(id);

  //获取实体的位置信息 但是获取到的是Cartesian3的坐标（三维笛卡尔坐标）
  let positions = entity.polyline.positions.getValue();

  //转化为Cartographic格式 弧度坐标
  let cartographics = positions.map((item) => {
    return Cesium.Cartographic.fromCartesian(item);
  }); //得到 Cartographic 格式的数组
  //转化为经纬度和高度
  let longitude = Cesium.Math.toDegrees(cartographics[0].longitude); //经度
  let latitude = Cesium.Math.toDegrees(cartographics[0].latitude); //纬度
  let height = cartographics[0].height;
  // 获取当前高度
  let currentHeight = viewer.camera.positionCartographic.height;
  // 定位到线的第一个点
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(
      longitude,
      latitude,
      currentHeight
    ),
    durationn: 2,
  });
}
function drawCircleToXXX(viewer, radius, longitude, latitude) {
  let position = Cesium.Cartesian3.fromDegrees(longitude, latitude, 0);
  const circle = viewer.entities.add({
    name: "Circle",
    position: position,
    ellipse: {
      semiMajorAxis: radius,
      semiMinorAxis: radius,
      material: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE),
    },
  });
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, 3000000),
    durationn: 2,
  });
}
function drawPolyGonToXXX(viewer, id, position) {
  const quadEntity = viewer.entities.add({
    id: id,
    polygon: {
      hierarchy: new Cesium.PolygonHierarchy(position),
      material: Cesium.Color.WHITE,
      height: 0,
    },
  });
  return quadEntity;
}
function PolyGonpositionToXXX(viewer, id) {
  let entity = viewer.entities.getById(id);
  console.log("这是拿到的笛卡尔坐标", entity.polygon);
  const hierarchy = entity.polygon.hierarchy.getValue(Cesium.JulianDate.now());
  console.log(hierarchy);
  let positions = hierarchy.positions;
  let cartographics = positions.map((item) => {
    return Cesium.Cartographic.fromCartesian(item);
  });
  let longitude = Cesium.Math.toDegrees(cartographics[0].longitude);
  let latitude = Cesium.Math.toDegrees(cartographics[0].latitude);
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, 3000000),
    durationn: 2,
  });
}
function updatePolyGonToXXX(viewer, id, pointaddress) {
  let entity = viewer.entities.getById(id);
  const hierarchy = entity.polygon.hierarchy.getValue();
  const positions = hierarchy.positions;
  const newCartesian = Cesium.Cartesian3.fromDegrees(
    pointaddress[0],
    pointaddress[1]
  );
  const newPositions = [
    positions[0],
    positions[1],
    newCartesian,
    positions[2],
    positions[3],
  ];
  // 更新多边形
  entity.polygon.hierarchy = new Cesium.PolygonHierarchy(newPositions);
  return entity;
}
function drawTextToXXX(viewer, id, longitude, latitude) {
  viewer.entities.add({
    id: id,
    position: Cesium.Cartesian3.fromDegrees(longitude, latitude),
    label: {
      text: "这是北京", // 要显示的文字
      font: "24px sans-serif", // 字体大小和类型
      style: Cesium.LabelStyle.FILL_AND_OUTLINE, // 样式
      outlineWidth: 2, // 轮廓线宽度
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM, // 垂直对齐方式
      pixelOffset: new Cesium.Cartesian2(0, -20), // 像素偏移
    },
  });
}
function LinearPointsArray(startLon, startLat, endLon, endLat, count) {
  const points = [];

  // 生成包括起点和终点在内的所有点
  for (let i = 0; i <= count + 1; i++) {
    const ratio = i / (count + 1);
    points.push({
      longitude: startLon + (endLon - startLon) * ratio,
      latitude: startLat + (endLat - startLat) * ratio,
    });
  }

  return points;
}
function drawRedLineTrajectoryToXXX(viewer, id, points) {
  // 默认配置
  const defaults = {
    pointColor: Cesium.Color.RED,
    pointSize: 6,
    outlineColor: Cesium.Color.WHITE,
    outlineWidth: 1,
    showLabels: false,
  };

  // 创建轨迹组实体
  const trajectoryGroup = viewer.entities.add({
    id: id,
    name: "红色直线轨迹",
    show: true,
  });

  // 为每个点创建红色点实体
  points.forEach((point) => {
    viewer.entities.add({
      parent: trajectoryGroup,
      position: Cesium.Cartesian3.fromDegrees(point.longitude, point.latitude),
      point: {
        pixelSize: defaults.pointSize,
        color: defaults.pointColor,
        outlineColor: defaults.outlineColor,
        outlineWidth: defaults.outlineWidth,
      },
    });
  });

  return trajectoryGroup;
}
function drawTrajectoryCircleToXXX(viewer, id, position, radius) {
  // 将圆心位置转换为笛卡尔坐标
  const center = Cesium.Cartesian3.fromDegrees(
    position.longitude,
    position.latitude,
    position.height || 0
  );

  // 创建圆环组实体
  const circleGroup = viewer.entities.add({
    id: id,
    name: "红点圆环",
    show: true,
  });

  // 圆环上的点数（根据半径自动调整）
  const pointCount = Math.max(36, Math.min(72, Math.floor(radius / 50)));

  // 创建圆环上的红点
  for (let i = 0; i < pointCount; i++) {
    const angle = (i / pointCount) * Math.PI * 2; // 当前角度

    // 计算圆环上的点位置
    const offset = new Cesium.Cartesian3(
      Math.cos(angle) * radius,
      Math.sin(angle) * radius,
      0
    );

    const pointPosition = Cesium.Cartesian3.add(
      center,
      offset,
      new Cesium.Cartesian3()
    );

    // 添加红点实体
    viewer.entities.add({
      parent: circleGroup,
      position: pointPosition,
      point: {
        pixelSize: 6, // 点大小
        color: Cesium.Color.RED, // 红色
        outlineColor: Cesium.Color.WHITE, // 白色轮廓
        outlineWidth: 1, // 轮廓宽度
      },
    });
  }
  return circleGroup;
}
function updatePointToXXX(viewer, id, position) {
  const oldEntity = viewer.entities.getById(id);
  if (oldEntity) {
    viewer.entities.remove(oldEntity);
  }

  // 将位置转换为笛卡尔坐标
  const cartesianPosition = Cesium.Cartesian3.fromDegrees(
    position.longitude,
    position.latitude,
    position.height || 0
  );

  // 3. 创建新的点实体
  const newPoint = viewer.entities.add({
    id: id,
    position: cartesianPosition,
    point: {
      pixelSize: 10, // 点大小
      color: Cesium.Color.WHITE, // 白色填充
      outlineColor: Cesium.Color.BLUE, // 蓝色边框
      outlineWidth: 2, // 边框宽度
    },
  });
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(
      position.longitude,
      position.latitude,
      3000000
    ),
    durationn: 2,
  });
  return newPoint;
}
function updateLineToXXX(viewer, id, lineArray) {
  const oldEntity = viewer.entities.getById(id);
  if (oldEntity) {
    viewer.entities.remove(oldEntity);
  }
  const positions = Cesium.Cartesian3.fromDegreesArrayHeights(lineArray);
  let line = viewer.entities.add({
    id: id,
    polyline: {
      width: 12,
      positions: positions,
      material: new Cesium.PolylineGlowMaterialProperty({
        color: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLUE,
        outlineWidth: 2,
      }),
      clampToGround: false,
    },
  });
}
function drawPlaneToXXX(viewer, id, position, url) {
  const planePosition = Cesium.Cartesian3.fromDegrees(
    position.longitude,
    position.latitude,
    position.height || 1000
  );

  const planeEntity = viewer.entities.add({
    id: id,
    position: planePosition,
    billboard: {
      image: url, // 飞机图片路径
      width: 40, // 像素宽度
      height: 40, // 像素高度
      rotation: -45, // 旋转角度(弧度)
      alignedAxis: Cesium.Cartesian3.UNIT_Z, // 对齐轴
      color: Cesium.Color.RED.withAlpha(0.9),
      scale: 1.0,
    },
  });

  return planeEntity;
}
function updatePlaneToXXX(viewer, id, position, url) {
  const oldEntity = viewer.entities.getById(id);
  if (oldEntity) {
    viewer.entities.remove(oldEntity);
  }
  const planePosition = Cesium.Cartesian3.fromDegrees(
    position.longitude,
    position.latitude,
    position.height || 1000
  );
  const planeEntity = viewer.entities.add({
    id: id,
    position: planePosition,
    billboard: {
      image: url,
      width: 40,
      height: 40,
      rotation: 45, // 旋转角度(弧度)
      alignedAxis: Cesium.Cartesian3.UNIT_Z, // 对齐轴
      color: Cesium.Color.WHITE.withAlpha(0.9),
      scale: 1.0,
    },
  });
  return planeEntity;
}
export default {
  initCesiumXXX,
  changemap,
  positionToXXX,
  drawPointToXXX,
  pointPositionToXXX,
  drawLineToXXX,
  linePositionToXXX,
  drawCircleToXXX,
  drawPolyGonToXXX,
  PolyGonpositionToXXX,
  updatePolyGonToXXX,
  drawTextToXXX,
  drawTrajectoryCircleToXXX,
  drawRedLineTrajectoryToXXX,
  LinearPointsArray,
  updatePointToXXX,
  updateLineToXXX,
  drawPlaneToXXX,
  updatePlaneToXXX,
};
